package com.example.week02.day2.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;


import com.example.week02.R;
import com.example.week02.day2.adapters.GridViewAdapter;
import com.example.week02.day2.adapters.ListViewAdapter;
import com.example.week02.day2.adapters.StaggerViewAdapter;
import com.example.week02.day2.beans.Datas;
import com.example.week02.day2.beans.ItemBean;

import java.util.ArrayList;
import java.util.List;

//RecyclerView实现ListView GridView 瀑布流
public class RecyclerView_1 extends AppCompatActivity {

    private static final String TAG = "menu---";

    RecyclerView recycler_view;
    private List<ItemBean> mData;
    private SwipeRefreshLayout refreshLayout;
    private ListViewAdapter listViewAdapter;
    private StaggerViewAdapter staggerViewAdapter;
    private GridViewAdapter gridViewAdapter;

    private ProgressBar progressLoading;
    private boolean isLoading = false; // 是否正在加载
    private boolean hasMore = true;    // 是否还有更多数据


    private RecyclerView.Adapter<?> currentAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_recycler_view1);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 绑定进度条
        progressLoading = findViewById(R.id.progress_loading);

        // 绑定 Toolbar 并设置为支持操作栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);  // 关键步骤：启用菜单支持
        //控制刷新
        refreshLayout = findViewById(R.id.refresh_layout);


        //找到RecyclerView
        recycler_view = findViewById(R.id.recycler_view);

        //准备数据
        initData();
        //设置默认的显示样式为ListView的效果
        showList(true, false);

        //处理下拉刷新
        handlerDownPullUpdate();

        // 添加上拉加载监听
        setupLoadMoreListener();
    }

    private void setupLoadMoreListener() {
        recycler_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                // 只有向上滚动时才检查
                if (dy <= 0 || isLoading || !hasMore) return;

                RecyclerView.LayoutManager layoutManager = recycler_view.getLayoutManager();
                if (layoutManager == null) return;

                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = 0;

                if (layoutManager instanceof LinearLayoutManager) {
                    firstVisibleItemPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                } else if (layoutManager instanceof GridLayoutManager) {
                    firstVisibleItemPosition = ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition();
                } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                    int[] positions = ((StaggeredGridLayoutManager) layoutManager).findFirstVisibleItemPositions(null);
                    if (positions.length > 0) {
                        firstVisibleItemPosition = positions[0];
                    }
                }

                // 检查是否滚动到底部
                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount >= 10) { // 至少有10个item时才触发
                    loadMoreData();
                }
            }
        });
    }

    /**
     * 上拉加载更多数据
     */
    private void loadMoreData() {
        if (isLoading) return;

        isLoading = true;
        progressLoading.setVisibility(View.VISIBLE);

        // 模拟加载延迟
        new Handler().postDelayed(() -> {
            // 添加新数据
            int startIndex = mData.size();
            for (int i = 0; i < 5; i++) { // 每次加载5条数据
                ItemBean data = new ItemBean();
                data.title = "上拉加载的数据 " + (startIndex + i);
                data.icon = Datas.icons[(startIndex + i) % Datas.icons.length];
                mData.add(data);
            }

            // 更新UI
            if (currentAdapter != null) {
                currentAdapter.notifyItemRangeInserted(startIndex, 5);
            }

            // 重置状态
            isLoading = false;
            progressLoading.setVisibility(View.GONE);

            // 模拟没有更多数据的情况（加载50条后不再加载）
            if (mData.size() >= 50) {
                hasMore = false;
                Toast.makeText(RecyclerView_1.this, "已加载所有数据", Toast.LENGTH_SHORT).show();
            }
        }, 1500); // 1.5秒延迟
    }

    //上拉加载，下拉刷新
    private void handlerDownPullUpdate() {

        refreshLayout.setEnabled(true);

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                // 下拉刷新时重置加载状态
                hasMore = true;


                //执行刷新数据的操作
                //一般开启新线程，这里演示直接添加一条数据
                ItemBean data = new ItemBean();
                data.title = "我是新添加的数据...";
                data.icon = R.drawable.r9;
                mData.add(0,data);
                //更新UI
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //让刷新停止，且更新列表
                        if (currentAdapter != null) {
                            currentAdapter.notifyItemInserted(0);
                        }
                        refreshLayout.setRefreshing(false);
                    }
                },1000);

                // 在刷新完成后滚动到顶部
                new Handler().postDelayed(() -> {
                    if (recycler_view != null && recycler_view.getLayoutManager() != null) {
                        recycler_view.getLayoutManager().scrollToPosition(0);
                    }
                }, 100);


            }
        });
    }

    //模拟数据
    private void initData() {
        //List<DataBea>----->Adapter----->setAdapter------>显示数据。
        mData = new ArrayList<>();

        for (int i = 0; i < Datas.icons.length; i++) {
            //创建数据对象
            ItemBean data = new ItemBean();
            data.icon = Datas.icons[i];
            data.title = "我是第" + i + "个条目";
            //添加到集合里头
            mData.add(data);
        }
    }


    //创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    //菜单被选中
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();

        if (itemId == R.id.list_view_vertical_stander) {
            Log.d(TAG, "点击了ListView中的垂直标准---");
            showList(true, false);
        } else if (itemId == R.id.list_view_vertical_reverse) {
            Log.d(TAG, "点击了ListView中的垂直反向---");
            showList(true, true);
        } else if (itemId == R.id.list_view_horizontal_stander) {
            Log.d(TAG, "点击了ListView中的水平标准---");
            showList(false, false);
        } else if (itemId == R.id.list_view_horizontal_reverse) {
            Log.d(TAG, "点击了ListView中的水平反向---");
            showList(false, true);
        } else if (itemId == R.id.grid_view_vertical_stander) {
            Log.d(TAG, "点击了GridView中的垂直标准---");
            showGrid(true, false);
        } else if (itemId == R.id.grid_view_vertical_reverse) {
            Log.d(TAG, "点击了GridView中的垂直反向---");
            showGrid(true, true);
        } else if (itemId == R.id.grid_view_horizontal_stander) {
            Log.d(TAG, "点击了GridView中的水平标准---");
            showGrid(false, false);
        } else if (itemId == R.id.grid_view_horizontal_reverse) {
            Log.d(TAG, "点击了GridView中的水平反向---");
            showGrid(false, true);
        } else if (itemId == R.id.stagger_view_vertical_stander) {
            Log.d(TAG, "点击了瀑布流中的垂直标准---");
            showStagger(true, false);
        } else if (itemId == R.id.stagger_view_vertical_reverse) {
            Log.d(TAG, "点击了瀑布流中的直反向---");
            showStagger(true, true);
        } else if (itemId == R.id.stagger_view_horizontal_stander) {
            Log.d(TAG, "点击了瀑布流中的水平标准---");
            showStagger(false, false);
        } else if (itemId == R.id.stagger_view_horizontal_reverse) {
            Log.d(TAG, "点击了瀑布流中的水平反向---");
            showStagger(false, true);
        } else if (itemId == R.id.more_type) {
            Log.d(TAG, "点击了多种条目类型---");
            //跳到新的Activity中实现
            Intent intent = new Intent(RecyclerView_1.this,MortType.class);
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }


    //设置列表布局
    private void showList(boolean isVertical, boolean isReverse) {
        //RecyclerView需要设置布局管理器 就是设置布局样式
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        //设置布局管理器来控制
        //设置水平还是垂直
        linearLayoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);
        //设置正向还是反向
        linearLayoutManager.setReverseLayout(isReverse);

        recycler_view.setLayoutManager(linearLayoutManager);
        //创建适配器
        listViewAdapter = new ListViewAdapter(mData);
        //设置到RecyclerView中
        recycler_view.setAdapter(listViewAdapter);
        // 关键：设置当前适配器
        currentAdapter = listViewAdapter;


        // 设置点击监听器
        listViewAdapter.setOnItemClickListener(new ListViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, ItemBean item) {

                // 处理点击事件
                Log.d("RecyclerViewClick", "Clicked position: ---" + position);
                Toast.makeText(RecyclerView_1.this,
                        item.title,
                        Toast.LENGTH_SHORT).show();

            }
        });


    }

    //设置瀑布流
    private void showStagger(boolean isVertical, boolean isReverse) {
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, isVertical ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.HORIZONTAL);
        staggeredGridLayoutManager.setReverseLayout(isReverse);
        recycler_view.setLayoutManager(staggeredGridLayoutManager);

        staggerViewAdapter = new StaggerViewAdapter(mData);
        recycler_view.setAdapter(staggerViewAdapter);

        currentAdapter = staggerViewAdapter;



        // 设置点击监听器
        staggerViewAdapter.setOnItemClickListener(new StaggerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, ItemBean item) {

                // 处理点击事件
                Log.d("RecyclerViewClick", "Clicked position: ---" + position);
                Toast.makeText(RecyclerView_1.this,
                        item.title,
                        Toast.LENGTH_SHORT).show();

            }
        });
    }

    //设置网格布局
    private void showGrid(boolean isVertical, boolean isReverse) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);
        gridLayoutManager.setReverseLayout(isReverse);

        recycler_view.setLayoutManager(gridLayoutManager);

        gridViewAdapter = new GridViewAdapter(mData);

        recycler_view.setAdapter(gridViewAdapter);

        currentAdapter = gridViewAdapter;

        // 设置点击监听器
        gridViewAdapter.setOnItemClickListener(new GridViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, ItemBean item) {

                // 处理点击事件
                Log.d("RecyclerViewClick", "Clicked position: ---" + position);
                Toast.makeText(RecyclerView_1.this,
                        item.title,
                        Toast.LENGTH_SHORT).show();

            }
        });
    }

}